package net.labthink.instrument.device.intelligent.industrialpc.codec;

import net.labthink.instrument.device.intelligent.industrialpc.message.industrialpcParams;
import net.labthink.instrument.device.base.message.AbstractPacket;
import net.labthink.instrument.device.intelligent.industrialpc.zigbee.ZigbeePacket;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

/**
 * industrialpc's MessageDecoder
 *
 * @version        1.0.0.0, Nov 17, 2010
 * @author         Moses
 */
public class industrialpcMessageDecoder implements MessageDecoder {

    public industrialpcMessageDecoder() {
//	super(industrialpcParams.PACKET_HEADER, industrialpcParams.PACKET_TAIL);// 添加包头
    }

    protected ZigbeePacket decodeBody(IoSession session, IoBuffer in) {
        byte[] zigbeeheader = new byte[5];
        in.get(zigbeeheader);
        int bodylength = zigbeeheader[4]&0xff;
        byte[] body = new byte[bodylength];
        in.get(body);
        byte zigbeetail = in.get();
       

        ZigbeePacket m = new ZigbeePacket(body);
        m.setZigbeehead(zigbeeheader);
        m.setZigbeetail(zigbeetail);
        return m;
    }

    public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
        // Return NEED_DATA if the whole header is not read yet.
//	if (in.remaining() < industrialpcParams.PACKET_HEADER_LEN) {
//	    return MessageDecoderResult.NEED_DATA;
//	}

        //未取出zigbee头时，返回缺少数据，继续等待。
        if (in.remaining() < industrialpcParams.zigbeehead) {
            return MessageDecoderResult.NEED_DATA;
        }
        //取包体长度
        byte bodylength = in.get(4);

        //如果包没有全部传输过来的话，返回缺少数据，继续等待。
        if (in.remaining() < 5 + bodylength + 1) {
            return MessageDecoderResult.NEED_DATA;
        } else {
            return MessageDecoderResult.OK;
        }

        // Return NOT_OK if not matches.
        //return MessageDecoderResult.NOT_OK;
    }

    public MessageDecoderResult decode(IoSession session, IoBuffer in,
            ProtocolDecoderOutput out) throws Exception {

        // Try to decode body
        ZigbeePacket pkt = decodeBody(session, in);
        // Return NEED_DATA if the body is not fully read.
        if (pkt == null) {
            return MessageDecoderResult.NEED_DATA;
        }
//        in.getShort(); // 跳过 'tail'.
        out.write(pkt);

        return MessageDecoderResult.OK;
    }

    public void finishDecode(IoSession session, ProtocolDecoderOutput out)
            throws Exception {
    }
}
